from flask import Flask, request
import threading
from insert_info import insert_info
import sys

############################################
#一个小坑
# import queue
# task_queue = queue.Queue(500)
# 使用queue.Queue 创建队列是只能在线程间数据通讯，
# 如果是跨进程的通讯就不行了，
# 这也是用这种写法在使用uwsgi部署时不成功的原因，而在测试下成功
# 跨进程通讯的队列请使用如下建立队列

from multiprocessing import Queue
task_queue = Queue(500)

def worker():#入库函数

    while True:
        task = task_queue.get()

        print(task, 'start')

        # insert_info(*task)

        try:
            insert_info(*task)

        except:

            # print(task, '任务出错')
            error_info = sys.exc_info()

            error_class = str(error_info[0])
            error_mes= str(error_info[1])
            error_site = str(error_info[2].tb_frame) 

            with open('insert_mysql_error.log', 'a') as f:
                f.write('\n\n')
                f.write(str([error_class, error_mes, error_site]))


t = threading.Thread(target = worker)#任务线程对象

t.start()#开始线程
###################################################

app = Flask(__name__)

@app.route('/', methods = ['POST'])
def insert_db():

    info = request.form#接收post信息

    host = info.get('host')
    url = info.get('url')
    tag = info.get('tag')

    if not host and url and tag:

        return  {'result': 'NO'}

    # insert_info(url, host, tag)
    task_queue.put((url, host, tag))#将提交过的来信息放入任务队列中

    return {'result': 'OK'}





if __name__ == '__main__':
    app.run(debug = True)
    
    

    